<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    img {
      width: 50%;
      max-width: 50%;
    }
  </style>
</head>

<body>
  
  <h2>img 显示 图片</h2>
  <p>
    <img src="https://cdn2.jianshu.io/assets/web/nav-logo-4c7bbafe27adc892f3046e6978459bac.png">
    <!-- 自行改图片地址 -->
  </p>

  <h2>canvas 画图</h2>
  <canvas id="canvas" width="750" height="1134" style="width: 100%; height:100%"></canvas>


  <script>

   const coverUrl = 'https://cdn2.jianshu.io/assets/web/nav-logo-4c7bbafe27adc892f3046e6978459bac.png?id=x';  //自行改图片地址
    const DrawCanvas = {
      async drawCover() {
        this.canvas = document.getElementById('canvas');
        this.context = this.canvas.getContext("2d");

       
        const coverUrlData = await LoadImage(coverUrl).catch(error => {
          return error;
        });
        coverUrlData && this.context.drawImage(
          coverUrlData,
          0,
          0,
          coverUrlData.width,
          coverUrlData.height,
          0,
          0,
          750,
          1134
        );

        const base64ImageData = this.canvas.toDataURL("image/jpeg");
        console.log(base64ImageData)
      }
    }
    const LoadImage = (url) => {
      var img = new Image();

      img.setAttribute("crossorigin", "anonymous");

      img.src = url;
      return new Promise((resolve, reject) => {
        img.onload = () => {
          resolve(img); //成功
        };
        img.onerror = () => {
          reject(); //失败
        };
      });
    }

    DrawCanvas.drawCover()
  </script>
</body>

</html>